import { Request, Response, NextFunction } from 'express'
import { Result, ajaxResultFail, Log } from './index';

// 错误对象
export class ApiBaseError {
  errCode: number
  errMsg: string

  constructor(errMsg = '', errCode = 500) {
    this.errMsg = errMsg
    this.errCode = errCode
  }
}

// 日志回调
export type LogCallback = (error: Result | ApiBaseError | Error) => void

export class ApiBaseErrorMidware {
  static LOG_CALLBACKS: LogCallback[] = []

  /**
   * 错误处理中间件
  */
  static midware(customAjaxResultFail?: typeof ajaxResultFail) {
    return function(error: Result | ApiBaseError | Error, req: Request, res: Response, next: NextFunction) {
      const handleFail = customAjaxResultFail || ajaxResultFail

      // 如果错误是字符串将它转成 Result
      if (typeof error === 'string') {
        error = handleFail(error)
      }

      // 触发回调
      ApiBaseErrorMidware.LOG_CALLBACKS.forEach(cb => cb(error))

      if (error instanceof Result) {
        return res.json(error)
      } else if (error instanceof ApiBaseError) {
        return res.json(handleFail(error.errMsg, error.errCode))
      } else if (error instanceof Error) {
        return res.json(handleFail(error.stack || error.message))
      }

      next()
    }
  }

  /**
   * 设置默认错误日志处理
  */
  static setDefaultLog(logPath?: string) {
    if (logPath) {
      Log.LOG_PATH = logPath
    }
    ApiBaseErrorMidware.LOG_CALLBACKS.push(Log.error)
  }
}